<template>
  <div class="platform-reports">
    <!-- 查询条件区域 -->
    <div class="query-section">
      <el-date-picker
        v-model="queryForm.startDate"
        type="date"
        placeholder="开始日期"
        value-format="yyyy-MM-dd"
        style="width: 150px; margin-right: 10px;"
      />
      <el-date-picker
        v-model="queryForm.endDate"
        type="date"
        placeholder="结束日期"
        value-format="yyyy-MM-dd"
        style="width: 150px; margin-right: 10px;"
      />
      <el-button type="primary" @click="fetchReportData" size="small">查询</el-button>
      <el-button @click="resetQuery" size="small">重置</el-button>
      <el-button type="success" @click="exportReport" size="small" style="float: right;">导出Excel</el-button>
    </div>

    <!-- 数据统计卡片区域 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-value">¥{{ totalBossSpent.toFixed(2) }}</div>
          <div class="stat-label">老板总消费</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-value">¥{{ totalPlaymateIncome.toFixed(2) }}</div>
          <div class="stat-label">陪玩总收入</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-value" :class="{ 'positive': netFlow >= 0, 'negative': netFlow < 0 }">
            ¥{{ netFlow.toFixed(2) }}
          </div>
          <div class="stat-label">净流水</div>
        </div>
      </el-card>
    </div>

     <!-- 图表容器 -->
    <div class="chart-section">
      <div ref="chartContainer" class="chart-container"></div>
    </div>

     <!-- 数据表格 -->
    <div class="table-section">
      <el-table :data="reportData" border style="width: 100%" size="small">
        <el-table-column prop="month" label="月份" width="120" />
        <el-table-column prop="bossSpentTotal" label="老板消费总额" width="150">
          <template #default="scope">
            ¥{{ scope.row.bossSpentTotal.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="playmateIncomeTotal" label="陪玩收入总额" width="150">
          <template #default="scope">
            ¥{{ scope.row.playmateIncomeTotal.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="bossTransactionCount" label="老板交易笔数" width="120" />
        <el-table-column prop="playmateTransactionCount" label="陪玩交易笔数" width="120" />
        <el-table-column prop="netFlow" label="净流水" width="120">
          <template #default="scope">
            <span :class="{ 'positive': scope.row.netFlow >= 0, 'negative': scope.row.netFlow < 0 }">
              ¥{{ scope.row.netFlow.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right;"
        background
      />
    </div>

  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data() {
    // 获取当前年月
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth(); // getMonth() 返回 0-11，0 表示一月
    // 计算当月第一天和最后一天
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    return {
      // 查询表单数据
      queryForm: {
        tenantId: 1,        // 租户ID（需要根据实际业务获取）
        pageNum: 1,         // 当前页码
        pageSize: 10,       // 每页显示条数
        startDate: this.formatDate(firstDay),      // 开始日期
        endDate: this.formatDate(lastDay)          // 结束日期
      },
      reportData: [], // 报表数据列表
      total: 0,       // 数据总条数
      chart: null    // ECharts实例对象
    };
  },
  // 计算属性
  computed:{
    // 老板总消费
    totalBossSpent() {
      return this.reportData.reduce((sum, item) => sum + (item.bossSpentTotal || 0), 0);
    },
    // 陪玩总收入
    totalPlaymateIncome() {
      return this.reportData.reduce((sum, item) => sum + (item.playmateIncomeTotal || 0), 0);
    },
    // 净流水
    netFlow() {
      return this.totalPlaymateIncome - this.totalBossSpent;
    }
  },
  methods:{
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 导出报表为Excel
    async exportReport() {
     const res = await this.financeApi.exportFinanceReport(this.queryForm);

      // 处理二进制文件下载
      if (res instanceof Blob) {
        const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '资金流水报表.xlsx');
        document.body.appendChild(link);
        link.click();
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      } else {
        this.$message.error('导出失败：服务器返回格式异常');
      }
    },
    // 重置查询条件
    resetQuery() {
      this.queryForm = {
        tenantId: 1,
        pageNum: 1,
        pageSize: 10,
        startDate: '',
        endDate: ''
      }
      this.fetchReportData();
    },
    // 处理每页显示条数变化
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.fetchReportData();
    },
    // 处理当前页变化
    handleCurrentChange(val) {
      this.queryForm.pageNum = val;
      this.fetchReportData();
    },
    //获取报表数据
    async fetchReportData(){
      const res = await this.financeApi.getFinanceReport(this.queryForm);
      if (res.code == 200) {
        this.reportData = res.data.list;
        this.total = res.data.total;
        // 在下次DOM更新后初始化图表
        this.$nextTick(() => {
          this.initChart();
        });
      }else{
        this.$message.error(res.message);
      }
    },
    //初始化ECharts图表
    initChart() {
      // 检查图表容器是否存在
      if (!this.$refs.chartContainer) return;
      // 如果已有图表实例，则先销毁
      if (this.chart) {
        this.chart.dispose();
      }
      // 初始化ECharts实例
      this.chart = echarts.init(this.$refs.chartContainer);
      // 提取图表所需数据
      const months = this.reportData.map(item => item.month);                           // 月份数据
      const bossSpent = this.reportData.map(item => item.bossSpentTotal);               // 老板消费数据
      const playmateIncome = this.reportData.map(item => item.playmateIncomeTotal);     // 陪玩收入数据
      const netFlow = this.reportData.map(item => item.netFlow); 
      // 图表配置项
      const option = {
        // 提示框配置
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            let tooltip = params[0].name + '<br/>';
            params.forEach(param => {
              tooltip += `${param.seriesName}: ¥${param.value.toFixed(2)}<br/>`;
            });
            return tooltip;
          }
        },
         // 图例配置
        legend: {
          data: ['老板消费总额', '陪玩收入总额', '净流水'],
          top: '10px'
        },
        // 网格配置
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        // X轴配置
        xAxis: {
          type: 'category',
          data: months,
          axisLabel: {
            fontSize: 12
          }
        },
        // Y轴配置
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '¥{value}',
            fontSize: 12
          }
        },
        // 系列数据配置
        series:[
          {
            name: '老板消费总额',
            type: 'bar',
            data: bossSpent,
            itemStyle: {
              color: '#5470c6'
            },
            barWidth: '6%', // 缩小柱子宽度
            barGap: '200%',   // 同一组内柱子间距
            barCategoryGap: '70%' // 不同组之间间距
          },
          {
            name: '陪玩收入总额',
            type: 'bar',
            data: playmateIncome,
            itemStyle: {
              color: '#8bc34a'
            },
            barWidth: '6%',
            barGap: '200%',
            barCategoryGap: '70%'
          },
          {
            name: '净流水',
            type: 'line',
            data: netFlow,
            itemStyle: {
              color: '#fac858'
            },
            smooth: true,
            yAxisIndex: 0
          }
        ],
      };
       // 设置图表配置
      this.chart.setOption(option);
      // 监听窗口大小变化，自适应图表
      window.addEventListener('resize', this.handleResize);
    },
    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
  }, 
  // 组件挂载完成后执行
  mounted() {
    // 初始化获取报表数据
    this.fetchReportData();
  },
  // 组件销毁前执行
  beforeUnmount() {
    // 销毁ECharts实例，防止内存泄漏
    if (this.chart) {
      this.chart.dispose();
    }
  },
};
</script>

<style scoped>
/* 页面容器样式 */
.platform-reports {
  padding: 20px;
  background-color: #f5f7fa;
}

/* 页面标题样式 */
.page-title {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

/* 查询条件区域样式 */
.query-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 统计卡片容器样式 */
.stats-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 20px;
}

/* 统计卡片样式 */
.stat-card {
  flex: 1;
  text-align: center;
}

/* 统计内容样式 */
.stat-content {
  padding: 20px 0;
}

/* 统计数值样式 */
.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #606266;
}

/* 正数样式 */
.stat-value.positive,
.positive {
  color: #67c23a;
}

/* 负数样式 */
.stat-value.negative,
.negative {
  color: #f56c6c;
}

/* 统计标签样式 */
.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 图表区域样式 */
.chart-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 图表容器样式 */
.chart-container {
  width: 100%;
  height: 400px;
}

/* 表格区域样式 */
.table-section {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards {
    flex-direction: column;
  }
  
  .query-section {
    text-align: center;
  }
}
</style>
